package thread;

/**
 * Creared with IntelliJ IDEA.
 * Description:线程不安全的解决办法加锁synchronized就可解决不同线程对同一资源进行操作所产生的的问题了
 * User:yxd
 * Date:2022-03-23
 * Time:13:48
 */
class Add1{
    public int count;
    synchronized public void increase(){
        count++;
    }
}
public class Demo14 {
    public static Add1 add = new Add1();
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5_0000; i++) {
                add.increase();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                add.increase();
            }
        });
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();//这两个join谁在前谁在后都是没有关系的因为我们并不知道t1,t2哪个先结束 但是并不影响因为main一定是会等到t1和t2都结束才会打印count的
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(add.count);
    }
}
